package com.sweets.look.ui.browser;

import android.content.Context;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.SortedMap;
import java.util.TreeMap;

import com.sweets.look.R;
import com.sweets.look.adapter.HistoryItem;
import com.sweets.look.constant.Constants;
import com.sweets.look.preference.PreferenceManager;
import com.sweets.look.util.ViewUtils;

import org.json.JSONException;
import org.json.JSONObject;

public class BookmarkManager {
    class OrderSort implements Comparator<HistoryItem> {

        public int compare(HistoryItem o1, HistoryItem o2) {
            return o1.getTitle().toLowerCase(Locale.getDefault()).compareTo(o2.getTitle().toLowerCase(
                    Locale.getDefault()));
        }
    }

    class WantedSort implements Comparator<HistoryItem> {

        public int compare(HistoryItem o1, HistoryItem o2) {
            return o2.getOrder() - o1.getOrder();
        }
    }

    public static final String FILE_BOOKMARKS = "bookmarks.dat";
    public static final String FOLDER = "folder";
    public static final String ORDER = "order";
    public static final String TITLE = "title";
    public static final String URL = "url";
    private static SortedMap<String, Integer> mBookmarkMap;
    private final Context mContext;

    static {
        BookmarkManager.mBookmarkMap = new TreeMap(String.CASE_INSENSITIVE_ORDER);
    }

    public BookmarkManager(Context context) {
        super();
        this.mContext = context;
        BookmarkManager.mBookmarkMap = this.getBookmarkUrls();
    }

    public synchronized boolean addBookmark(HistoryItem item) {
        boolean isSuccess = true;
        File file = BookmarkManager.getBookmarksFile(this.mContext);
        if (!mBookmarkMap.containsKey(item.getUrl())) {
            BufferedWriter writer;
            try {
                writer = new BufferedWriter(new FileWriter(file, true));
                JSONObject json = new JSONObject();
                try {
                    json.put("title", item.getTitle());
                    json.put("url", item.getUrl());
                    json.put("folder", item.getFolder());
                    json.put("order", item.getOrder());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                writer.write(json.toString());
                writer.newLine();
                writer.close();
                mBookmarkMap.put(item.getUrl(), 1);
            } catch (IOException e) {
                e.printStackTrace();
                isSuccess = false;
            }
        } else {
            isSuccess = false;
        }
        return isSuccess;
    }

    private synchronized void addBookmarkList(List<HistoryItem> arg10) {
        BufferedWriter v0 = null;

        File v1 = BookmarkManager.getBookmarksFile(this.mContext);
        try {
            v0 = new BufferedWriter(new FileWriter(v1, true));
            Iterator<HistoryItem> v5_3 = arg10.iterator();
            while (v5_3.hasNext()) {
                HistoryItem v3 = v5_3.next();
                if (BookmarkManager.mBookmarkMap.containsKey(((HistoryItem) v3).getUrl())) {
                    continue;
                }

                JSONObject v4 = new JSONObject();
                v4.put("title", ((HistoryItem) v3).getTitle());
                v4.put("url", ((HistoryItem) v3).getUrl());
                v4.put("folder", ((HistoryItem) v3).getFolder());
                v4.put("order", ((HistoryItem) v3).getOrder());
                v0.write(v4.toString());
                v0.newLine();
                BookmarkManager.mBookmarkMap.put(((HistoryItem) v3).getUrl(), Integer.valueOf(1));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (v0 != null) {
                try {
                    v0.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    public synchronized boolean deleteBookmark(String url) {
        BufferedWriter v3 = null;
        boolean v0 = false;
        if (url == null) {
            return false;
        }
        BookmarkManager.mBookmarkMap.remove(url);
        List v5 = this.getBookmarks();
        File v1 = BookmarkManager.getBookmarksFile(this.mContext);
        v0 = false;
        try {
            v3 = new BufferedWriter(new FileWriter(v1, false));
            Iterator v7_3 = v5.iterator();
            while (true) {
                if (!v7_3.hasNext()) {
                    return v0;
                }

                Object v4 = v7_3.next();
                if (((HistoryItem) v4).getUrl().equalsIgnoreCase(url)) {
                    v0 = true;
                    continue;
                }

                JSONObject v6 = new JSONObject();
                v6.put("title", ((HistoryItem) v4).getTitle());
                v6.put("url", ((HistoryItem) v4).getUrl());
                v6.put("folder", ((HistoryItem) v4).getFolder());
                v6.put("order", ((HistoryItem) v4).getOrder());
                v3.write(v6.toString());
                v3.newLine();
            }

        } catch (JSONException e) {

        } catch (IOException e) {
        } finally {
            if (v3 != null) {
                try {
                    v3.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return v0;
    }

    public synchronized void exportBookmarks() {

        BufferedWriter v3 = null;
        File v4;

        List v2 = this.getBookmarks();
        String v9 = this.mContext.getResources().getString(R.string.app_name) + "_" + this.mContext.getResources()
                .getString(R.string.bookmarks_file) + "_" + new SimpleDateFormat("yyyyMMdd", Locale.US).format(
                new Date(System.currentTimeMillis()));
        String v14 = Constants.EXTERNAL_STORAGE + "/" + PreferenceManager.getInstance().getDownloadDirectory()
                + "/";
        File v7 = new File(v14);
        if (!v7.exists()) {
            v7.mkdirs();
        }

        StringBuilder v15_1 = new StringBuilder();
        v4 = new File(v14, v15_1.append(v9).append(".txt").toString());
        int v5 = 0;
        while (v4.exists()) {
            ++v5;
            v4 = new File(v14, v9 + "_" + v5 + ".txt");
        }

        try {
            v3 = new BufferedWriter(new FileWriter(v4, false));
            Iterator v15_4 = v2.iterator();
            while (v15_4.hasNext()) {
                Object v11 = v15_4.next();
                JSONObject v13 = new JSONObject();
                v13.put("title", ((HistoryItem) v11).getTitle());
                v13.put("url", ((HistoryItem) v11).getUrl());
                v13.put("folder", ((HistoryItem) v11).getFolder());
                v13.put("order", ((HistoryItem) v11).getOrder());
                v3.write(v13.toString());
                v3.newLine();
            }


            ViewUtils.showToast(this.mContext.getString(R.string.bookmark_export_path) + " " + v4.getPath(), this.mContext);
        } catch (IOException e) {
        } catch (JSONException e) {
        } finally {
            if (v3 != null) {
                try {
                    v3.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获得所有标签
     *
     * @return
     */
    public synchronized List<HistoryItem> getAllBookmarks() {
        BufferedReader bufferedReader = null;
        ArrayList<HistoryItem> v0 = new ArrayList<>();
        ArrayList<HistoryItem> v5 = new ArrayList<>();
        ArrayList<HistoryItem> v1 = new ArrayList<>();
        TreeMap<String, Integer> v6 = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        File file = getBookmarksFile(this.mContext);
        try {
            bufferedReader = new BufferedReader(new FileReader(file));
            while (true) {
                String oneLine = bufferedReader.readLine();
                if (oneLine == null) {
                    break;
                }

                JSONObject jsonObject = new JSONObject(oneLine);
                String _folder = jsonObject.getString("folder");
                if (_folder.isEmpty()) {
                    HistoryItem item = new HistoryItem();
                    item.setTitle(jsonObject.getString("title"));
                    item.setUrl(jsonObject.getString("url"));
                    item.setFolder(jsonObject.getString("folder"));
                    item.setOrder(jsonObject.getInt("order"));
                    item.setImageId(R.drawable.ic_bookmark);
                    v1.add(item);
                    continue;
                }

                if (v6.containsKey(_folder)) {
                    continue;
                }

                HistoryItem item = new HistoryItem();
                item.setTitle(_folder);
                item.setUrl("folder://" + URLEncoder.encode(_folder, "utf-8"));
                item.setOrder(-1);
                v6.put(_folder, 1);
                v5.add(item);
            }

        } catch (JSONException | IOException e) {
            e.printStackTrace();
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e1) {
                }
            }
        }

        Collections.sort(v5, new OrderSort());
        Collections.sort(v1, new OrderSort());
        v0.clear();
        v0.addAll(v5);
        v0.addAll(v1);

        return v0;
    }

    private static String getBookmarkFolder(String line) {
        line = line.substring(0, line.length() - 5);
        return line.substring(line.lastIndexOf("\">") + 2, line.length());
    }

    private static String getBookmarkTitle(String line) {
        line = line.substring(0, line.length() - 4);
        return line.substring(line.lastIndexOf("\">") + 2, line.length());
    }

    private static String getBookmarkURL(String line) {
        String v2_1;
        String v1;
        int v6 = 6;
        String[] v3 = line.split(" +");
        int v4 = v3.length;
        int v2 = 0;
        while (true) {
            if (v2 < v4) {
                v1 = v3[v2];
                if (!v1.startsWith("href=\"") && !v1.startsWith("HREF=\"")) {
                    ++v2;
                    continue;
                }

                break;
            } else {
                return "";
            }
        }

        int v0 = v1.lastIndexOf("\">");
        if (v0 == -1) {
            v2_1 = v1.substring(v6, v1.length() - 1);
        } else {
            return v1.substring(v6, v0);
        }

        return v2_1;
    }

    /**
     * @return
     */
    private synchronized SortedMap<String, Integer> getBookmarkUrls() {
        BufferedReader reader = null;
        TreeMap<String, Integer> v4 = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        File v0 = BookmarkManager.getBookmarksFile(this.mContext);
        try {
            reader = new BufferedReader(new FileReader(v0));
            while (true) {
                String v3 = reader.readLine();
                if (v3 == null) {
                    break;
                }

                v4.put(new JSONObject(v3).getString("url"), 1);
            }
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return v4;
    }

    public synchronized List<HistoryItem> getBookmarks() {
        BufferedReader reader = null;
        ArrayList<HistoryItem> v0 = new ArrayList<>();
        File v1 = BookmarkManager.getBookmarksFile(this.mContext);
        try {
            reader = new BufferedReader(new FileReader(v1));
            String line;
            while ((line = reader.readLine()) != null) {
                JSONObject jsonObject = new JSONObject(line);
                HistoryItem v4 = new HistoryItem();
                v4.setTitle(jsonObject.getString("title"));
                v4.setUrl(jsonObject.getString("url"));
                v4.setFolder(jsonObject.getString("folder"));
                v4.setOrder(jsonObject.getInt("order"));
                v4.setImageId(R.drawable.ic_bookmark);
                v0.add(v4);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Collections.sort(v0, new OrderSort());
        return v0;
    }

    public static File getBookmarksFile(Context context) {
        if (!context.getFilesDir().exists()) {
            context.getFilesDir().mkdirs();
        }

        File file = new File(context.getFilesDir(), "bookmarks.dat");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return file;
    }

    public synchronized List<HistoryItem> getBookmarksFromFolder(String folder) {
        BufferedReader reader = null;
        ArrayList<HistoryItem> v0 = new ArrayList<>();
        File v1 = getBookmarksFile(this.mContext);
        try {
            reader = new BufferedReader(new FileReader(v1));
            HistoryItem v5 = new HistoryItem();
            v5.setTitle("...");
            v5.setOrder(-1);
            v5.setUrl("folder://");
            v0.add(v5);
            while (true) {
                String readLine = reader.readLine();
                if (readLine == null) {
                    break;
                }
                JSONObject jsonObject = new JSONObject(readLine);
                if (!URLEncoder.encode(jsonObject.getString("folder"), "utf-8").equals(folder)) {
                    continue;
                }

                HistoryItem item = new HistoryItem();
                item.setTitle(jsonObject.getString("title"));
                item.setUrl(jsonObject.getString("url"));
                item.setFolder(jsonObject.getString("folder"));
                item.setOrder(jsonObject.getInt("order"));
                item.setImageId(R.drawable.ic_bookmark);
                v0.add(item);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        Collections.sort(v0, new OrderSort());
        return v0;

    }

    public synchronized String[] getFolders() {
        HashSet<String> v5;
        v5 = new HashSet();
        TreeMap v3 = new TreeMap(String.CASE_INSENSITIVE_ORDER);
        File v0 = BookmarkManager.getBookmarksFile(this.mContext);
        try {
            BufferedReader v1 = new BufferedReader(new FileReader(v0));
            String v6;
            while ((v6 = v1.readLine()) != null) {
                String v4 = new JSONObject(v6).getString("folder");
                if (v4.isEmpty()) {
                    continue;
                }

                if (((SortedMap) v3).containsKey(v4)) {
                    continue;
                }

                v3.put(v4, Integer.valueOf(1));
                v5.add(v4);
            }

            v1.close();
        } catch (IOException v8_1) {
        } catch (JSONException v8_2) {
        }


        return v5.toArray(new String[v5.size()]);
    }

    public synchronized List<HistoryItem> getWantedBookmarks() {
        BufferedReader reader;
        ArrayList<HistoryItem> result = new ArrayList<>();
        File v1 = getBookmarksFile(this.mContext);
        try {
            reader = new BufferedReader(new FileReader(v1));
            String line;
            while ((line = reader.readLine()) != null) {
                JSONObject jsonObject = new JSONObject(line);
                HistoryItem v4 = new HistoryItem();
                v4.setTitle(jsonObject.getString("title"));
                v4.setUrl(jsonObject.getString("url"));
                v4.setFolder(jsonObject.getString("folder"));
                v4.setOrder(jsonObject.getInt("order"));
                if (jsonObject.getInt("order") > 0) {
                    result.add(v4);
                }
            }
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
        Collections.sort(result, new WantedSort());
        return result.subList(0, Math.min(8, result.size()));
    }

    public synchronized void importBookmarksFromHtml(File file) {
        if (file != null) {
            ArrayList v5 = new ArrayList();
            try {
                BufferedReader v0 = new BufferedReader(new FileReader(file));
                int v6 = 0;
                String v2 = "";
                String v4;
                while ((v4 = v0.readLine()) != null) {
                    v4 = v4.trim();
                    if ((v4.startsWith("<dt><h3 ")) && (v4.endsWith("</h3>"))) {
                        v2 = BookmarkManager.getBookmarkFolder(v4);
                    } else if ((v4.startsWith("<DT><H3 ")) && (v4.endsWith("</H3>"))) {
                        v2 = BookmarkManager.getBookmarkFolder(v4);
                    }

                    if ((v4.endsWith("</DL><p>")) || (v4.endsWith("</DL><P>")) || (v4.endsWith("</dl><p>"))
                            ) {
                        v2 = "";
                    }

                    if (!v4.startsWith("<dt><a ") || !v4.endsWith("</a>")) {
                        if (!v4.startsWith("<DT><A ")) {
                            continue;
                        }

                        if (!v4.endsWith("</A>")) {
                            continue;
                        }
                    }

                    String v7 = BookmarkManager.getBookmarkTitle(v4);
                    String v8 = BookmarkManager.getBookmarkURL(v4);
                    if (v7.trim().isEmpty()) {
                        continue;
                    }

                    if (v8.trim().isEmpty()) {
                        continue;
                    }

                    HistoryItem v3 = new HistoryItem();
                    v3.setTitle(v7);
                    v3.setUrl(v8);
                    v3.setFolder(v2);
                    ((List) v5).add(v3);
                    ++v6;
                    continue;
                }

                v0.close();
                this.addBookmarkList(((List) v5));
                ViewUtils.showToast(v6 + " " + this.mContext.getResources().getString(
                        R.string.message_import), mContext);
            } catch (Exception v1) {
                ViewUtils.showToast(this.mContext.getResources().getString(R.string.import_bookmark_error), mContext);
            }

        }

    }

    public synchronized void importBookmarksFromTxt(File file) {
        if (file != null) {
            ArrayList v4 = new ArrayList();
            try {
                BufferedReader v0 = new BufferedReader(new FileReader(file));
                int v5 = 0;
                String v3;
                while ((v3 = v0.readLine()) != null) {
                    JSONObject v6 = new JSONObject(v3);
                    HistoryItem v2 = new HistoryItem();
                    v2.setTitle(v6.getString("title"));
                    v2.setUrl(v6.getString("url"));
                    v2.setFolder(v6.getString("folder"));
                    v2.setOrder(v6.getInt("order"));
                    ((List) v4).add(v2);
                    ++v5;
                }

                v0.close();
                this.addBookmarkList(((List) v4));
                ViewUtils.showToast(v5 + " " + this.mContext.getResources().getString(
                        R.string.message_import), mContext);
                return;
            } catch (IOException e) {
            } catch (JSONException e) {
            }
            ViewUtils.showToast(this.mContext.getResources().getString(R.string.import_bookmark_error), mContext);
        }

        return;
    }

    public static void overwriteBookmarkList(Context context, List<HistoryItem> arg11) {
        BufferedWriter v0 = null;
        synchronized (BookmarkManager.class) {
            File v1 = BookmarkManager.getBookmarksFile(context);
            try {
                v0 = new BufferedWriter(new FileWriter(v1, false));
                BookmarkManager.mBookmarkMap.clear();
                Iterator v5_3 = arg11.iterator();
                while (v5_3.hasNext()) {
                    Object v3 = v5_3.next();
                    if (BookmarkManager.mBookmarkMap.containsKey(((HistoryItem) v3).getUrl())) {
                        continue;
                    }

                    JSONObject v4 = new JSONObject();
                    v4.put("title", ((HistoryItem) v3).getTitle());
                    v4.put("url", ((HistoryItem) v3).getUrl());
                    v4.put("folder", ((HistoryItem) v3).getFolder());
                    v4.put("order", ((HistoryItem) v3).getOrder());
                    v0.write(v4.toString());
                    v0.newLine();
                    BookmarkManager.mBookmarkMap.put(((HistoryItem) v3).getUrl(), Integer.valueOf(1));
                }
            } catch (IOException e) {
            } catch (JSONException e) {
            } finally {
                if (v0 != null) {
                    try {
                        v0.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public synchronized void overwriteBookmarks(List arg9) {
        BufferedWriter v0 = null;
        File v1 = BookmarkManager.getBookmarksFile(this.mContext);
        try {
            v0 = new BufferedWriter(new FileWriter(v1, false));
            Iterator v5_3 = arg9.iterator();
            while (v5_3.hasNext()) {
                Object v3 = v5_3.next();
                JSONObject v4 = new JSONObject();
                v4.put("title", ((HistoryItem) v3).getTitle());
                v4.put("url", ((HistoryItem) v3).getUrl());
                v4.put("folder", ((HistoryItem) v3).getFolder());
                v4.put("order", ((HistoryItem) v3).getOrder());
                v0.write(v4.toString());
                v0.newLine();
            }
        } catch (JSONException e) {
        } catch (IOException e) {
        } finally {
            if (v0 != null) {
                try {
                    v0.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public synchronized void renameFolder(String folder, String target) {
        BufferedWriter v0 = null;
        List v4 = this.getBookmarks();
        File v1 = BookmarkManager.getBookmarksFile(this.mContext);
        try {
            v0 = new BufferedWriter(new FileWriter(v1, false));
            Iterator v6_3 = v4.iterator();
            while (v6_3.hasNext()) {
                Object v3 = v6_3.next();
                JSONObject v5 = new JSONObject();
                v5.put("title", ((HistoryItem) v3).getTitle());
                v5.put("url", ((HistoryItem) v3).getUrl());
                v5.put("folder", ((HistoryItem) v3).getFolder());
                v5.put("order", ((HistoryItem) v3).getOrder());
                if (((HistoryItem) v3).getFolder().equalsIgnoreCase(folder)) {
                    v5.put("folder", target);
                }

                v0.write(v5.toString());
                v0.newLine();
            }
        } catch (IOException e) {
        } catch (JSONException e) {
        } finally {
            if (v0 != null) {
                try {
                    v0.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

